<?php
namespace Api\Controller;
use Think\Controller;
class SendController extends Controller {
	
	/**
	 * 创蓝短信发送
	 * @param string $mobile 		手机号码
	 * @param string $msg 			短信内容
	 * @param string $needstatus 	是否需要状态报告
	 */
	public function sendSMS( $mobile, $msg, $needstatus = 'true') {
		$api_account='';      //创蓝短信账户
		$api_password='';     //创蓝短信秘钥
		$api_send_url='http://vsms.253.com/msg/send/json';
		$API_VARIABLE_URL='http://vsms.253.com/msg/variable/json';
		$api_balance_query_url='http://vsms.253.com/msg/balance/json';
		
		//创蓝接口参数
		$postArr = array (
			'account'  =>  $api_account,
			'password' => $api_password,
			'msg' => urlencode($msg),
			'phone' => $mobile,
			'report' => $needstatus
        );
		
		$result = $this->curlPost( $api_send_url , $postArr);
		return $result;
	}


	/**
	 * 短信发送接口
	 * @param string $mobile  //接收短信手机号
	 */
	public function sendCode($mobile)
	{

		$code = mt_rand(000000,999999);//生成6位验证码随机数
		$result = $this->sendSMS($mobile, '【xxxxx】您好，您的注册验证码是'. $code);
		if(!is_null(json_decode($result))){
			
			$output=json_decode($result,true);
			if(isset($output['code'])  && $output['code']=='0'){
				//发送短信成功，进行业务操作
				$this->success('发送成功');
				
			}
		}else{
			$this->error('发送失败');
		}
		
	}
	

	/**
	 * 通过CURL发送HTTP请求
	 * @param string $url  //请求URL
	 * @param array $postFields //请求参数 
	 * @return mixed
	 */
	private function curlPost($url,$postFields){
		$postFields = json_encode($postFields);
		$ch = curl_init ();
		curl_setopt( $ch, CURLOPT_URL, $url ); 
		curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json; charset=utf-8'
			)
		);
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt( $ch, CURLOPT_TIMEOUT,1); 
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
		$ret = curl_exec ( $ch );
        if (false == $ret) {
            $result = curl_error(  $ch);
        } else {
            $rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "请求状态 ". $rsp . " " . curl_error($ch);
            } else {
                $result = $ret;
            }
        }
		curl_close ( $ch );
		return $result;
	}

}